package com.bs.regsystemapi.service;

import com.aliyuncs.exceptions.ClientException;

import com.bs.regsystemapi.entity.Result;
import com.bs.regsystemapi.utils.SMSUtils;
import com.bs.regsystemapi.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: ning
 * @description 发送验证码
 * @date: 2023-01-23 12:21
 */
@Service
public class ValidateCodeService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送验证码
     * @return
     */
    public Result validateCode(String telephone) throws ClientException {
        //生成4位数字验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        //发送短信
        SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());
        System.out.println("发送的手机验证码为：" + code);
        //将生成的验证码缓存到redis
        redisTemplate.opsForValue().set(telephone+"001",
                                        code.toString(),5*60, TimeUnit.SECONDS);
        return Result.success("验证码发送成功");
    }

    /**
     * 手机登录发送验证码
     * @param telephone
     * @return
     */
    public Result send4Login(String telephone){
        //生成6位数字验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        try {
            //发送短信
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            //验证码发送失败
            return Result.error("验证码发送失败");
        }
        System.out.println("发送的手机验证码为：" + code);
        //将生成的验证码缓存到redis
        redisTemplate.opsForValue().set(telephone+"002",
                code.toString(),5*60, TimeUnit.SECONDS);
        //验证码发送成功
        return Result.success("验证码发送成功");
    }
}
